
package com.rasenhund.android.grecorder.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.rasenhund.android.grecorder.R;
import com.rasenhund.android.grecorder.adapter.StageListAdapter;
import com.rasenhund.android.grecorder.common.Const;
import com.rasenhund.android.grecorder.dao.RecordDao;
import com.rasenhund.android.grecorder.helper.DbHelper;
import com.rasenhund.android.grecorder.schema.StageRecord;

/**
 * 結果表示画面
 */
public class ResultStageListActivity extends Activity {
    @SuppressWarnings("unused")
    private static final String TAG = ResultStageListActivity.class.getSimpleName();
    private final ResultStageListActivity self = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result_stage);

        initeView();

    }

    final OnItemClickListener lstResult_OnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            jumpCategory((int) id);
        }

    };

    /**
     * Viewの初期化
     */
    private void initeView() {

        ArrayList<StageRecord> list = Const.getStageList(self);
        for (int i = 0; i < list.size(); i++) {

            getStageResult(list.get(i));

        }

        StageListAdapter adapter = new StageListAdapter(self, list);

        ListView lstResult = (ListView) findViewById(R.id.lstResultStage);
        lstResult.setOnItemClickListener(lstResult_OnItemClickListener);
        lstResult.setAdapter(adapter);

    }

    /**
     * 戦績の取得
     * 
     * @param stage
     */
    private void getStageResult(StageRecord stage) {

        DbHelper dbHelper = null;
        SQLiteDatabase db = null;

        try {

            dbHelper = new DbHelper(self);
            db = dbHelper.getWritableDatabase();
            RecordDao dao = new RecordDao(db);

            dao.getResult(stage);

        } finally {
            if (db.isOpen()) {
                db.close();
            }
        }

        stage.calcPerWin();

    }

    /**
     * カテゴリ選択画面呼び出し
     */
    private void jumpCategory(int stageId) {

        Intent intent = new Intent(self, ResultCategoryActivity.class);
        intent.putExtra(Const.KEY.KEY_STAGE, stageId);
        startActivity(intent);

    }
}
